package org.jsola.hr.web;

import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.InstitutionAddDTO;
import org.jsola.hr.dto.InstitutionOpenDTO;
import org.jsola.hr.dto.InstitutionUpdateDTO;
import org.jsola.hr.entity.InstitutionDO;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.InstitutionQuery;
import org.jsola.hr.service.IInstitutionService;
import org.jsola.hr.vo.InstitutionListVO;
import org.jsola.hr.vo.InstitutionVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.Valid;


/**
 * 制度
 *
 * @author zhr
 */
@RestController("hrInstitutionController")
@RequestMapping(HrConstants.API_PATH + "/v1/institutions")
public class InstitutionController implements IInstitutionControllerAPI {

    @Autowired
    private IInstitutionService institutionService;

    @Autowired
    private IUserProviderService userProviderService;

    @Override
    @PostMapping
    public Result<InstitutionVO> save(@Valid @RequestBody InstitutionAddDTO institutionAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增制度权限校验

        return Result.success(
                institutionService.save(institutionAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody InstitutionUpdateDTO institutionUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改制度权限校验

        int count = institutionService.update(institutionUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping("/openInstitution")
    public Result<Integer> openInstitution(@RequestBody @Valid InstitutionOpenDTO institutionOpenDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改制度权限校验

        int count = institutionService.openInstitution(institutionOpenDTO.getInstitutionId(), tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping("/closeInstitution")
    public Result<Integer> closeInstitution(@RequestBody @Valid InstitutionOpenDTO institutionOpenDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改制度权限校验

        int count = institutionService.closeInstitution(institutionOpenDTO.getInstitutionId(), tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{institutionId}")
    public Result<Integer> delete(@PathVariable String institutionId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除制度权限校验

        int count = institutionService.deleteByIds(tokenUser, institutionId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] institutionIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除制度权限校验

        int count = institutionService.deleteByIds(tokenUser, institutionIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{institutionId}")
    public Result<InstitutionVO> findById(@PathVariable String institutionId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看制度权限校验

        return Result.success(
            institutionService.selectById(institutionId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<InstitutionListVO>> listAll(@Valid InstitutionQuery institutionQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看制度权限校验

        return Result.success(
            institutionService.select(institutionQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<InstitutionListVO>> page(@Valid InstitutionQuery institutionQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            institutionService.selectPage(institutionQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/selectByTypeIdAndCompanyId")
    public Result<Page<InstitutionListVO>> selectByTypeIdAndCompanyId(@Valid String institutionTypeId
            , String companyId, Integer pageNo, Integer pageSize) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        Page<InstitutionDO> page = institutionService.selectByTypeIdAndCompanyId(institutionTypeId
                , companyId, pageNo, pageSize, tokenUser.getSiteId());
        Page<InstitutionListVO> institutionListVOPage = page.to(InstitutionListVO.class);
        // 放入最后编辑人
        List<InstitutionListVO> pageEntities = institutionListVOPage.getEntities();
        List<String> modifiedUserIds = pageEntities.parallelStream()
                .map(InstitutionListVO::getModifiedUserId).distinct().collect(Collectors.toList());
        List<UserDO> userDOList = userProviderService.selectUserByIds(modifiedUserIds);
        // 编辑人Id-名称
        Map<String, String> userIdNameMap = userDOList.parallelStream()
                .collect(Collectors.toMap(BaseDO::getId, UserDO::getName));
        pageEntities.parallelStream().forEach(institutionListVO -> institutionListVO.setModifiedUserName(
                userIdNameMap.get(institutionListVO.getModifiedUserId())));
        return Result.success(
                institutionListVOPage
        );
    }

    @Override
    @GetMapping("/selectOpenByCompanyId")
    public Result<List<InstitutionListVO>> selectOpenByCompanyId(String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验


        return Result.success(
                institutionService.selectOpenByCompanyId(companyId, tokenUser.getSiteId())
        );
    }


}

